# 文件中写入文本
import codecs
import json
from json import JSONDecodeError
from typing import List


# # 文本操作
# with codecs.open('写入test.txt', 'w', encoding='utf-8') as file:
#     text = "hello呀";
#     file.write(text);
#
#
# # 二进制数据操作-写入
# with codecs.open('写入二进制数据.txt', 'wb') as file:
#     text = b'hello';
#     file.write(text);

# 二进制数据操作-读取 with自动关闭读写流
# with codecs.open('写入二进制数据.txt', 'rb', encoding=None) as file:
#     text = file.read();
#     # file.readline();
#     print(text);
# # 二进制数据操作-读取
# with codecs.open('写入二进制数据.txt', 'rb') as file:
#     text = file.read();
#     print(text);


def read_json(filename: str, encoding='utf-8') -> []:
    """
    按行读取文件内容
    :param filename:
    :param encoding:
    :return:
    """
    with codecs.open(filename, 'r', encoding=encoding) as file:
        return json.load(file);
    # return list(file)


def read_data(filename: str, encoding='utf-8') -> []:
    with codecs.open(filename, 'r', encoding=encoding) as file:
        try:
            for line in file:
                text=line.strip();
                print(text);
                # print(json.loads(text))
        except JSONDecodeError:
            print("json解析错误")
        # return [json.loads(line.strip()) for line in file if line.strip() != ''];
        #     print(type(line),line.strip(),end='')
        # return [line.strip() for line in file if line.strip() != ''];


if __name__ == '__main__':
    data = read_data('user.data');
    print(type(data), data)
    data = read_json('user.json');
    print(type(data), data)
    # print(read_json('user.json'));
    # print(type(['a', 'b']));
    # print(type({'a', 'b'}));
